<?php

namespace app\admin\controller\mall;

use app\admin\model\MallProject;
use app\admin\traits\Curd;
use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use EasyAdmin\tool\CommonTool;
use jianyan\excel\Excel;
use think\App;
use think\facade\Db;

/**
 * @ControllerAnnotation(title="项目管理")
 */
class Project extends AdminController
{

    use Curd;

    protected $relationSerach = true;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new MallProject();
    }

    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        $param      = request()->param();
        $project_id = isset($param['project_id']) ? $param['project_id'] : 1;
        if ($this->request->isAjax()) {
            if (isset($param['reference'])) {
                $reference = $param['reference'];
            } else {
                $reference = "";
            }

            $data = getRetrievalArchive($project_id, $reference, $param['page'], $param);

            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $data['total'],
                'data'  => $data['data'],
            ];
            return json($data);
        }
        $supervisor   = Db::name('mall_supervisor')->where(['project_id' => $project_id, 'del_date' => 0, ['sort', '<>', 0]])->field('id,supervisor_name')->order('sort')->select();
        $construction = Db::name('mall_construction')->where(['project_id' => $project_id, 'del_date' => 0, ['sort', '<>', 0]])->field('id,construction_name')->order('sort')->select();
        $supervisor   = $supervisor->toArray();
        $construction = $construction->toArray();
        foreach ($supervisor as &$v) {
            $v['type'] = 2;
            $v['name'] = $v['supervisor_name'];
        }
        foreach ($construction as &$v1) {
            $v1['type'] = 3;
            $v1['name'] = $v1['construction_name'];
        }

        $arr = array_merge($supervisor, $construction);
        //获取责任者
        $duty = Db::name('mall_duty')->field('id,name')->select();
        $duty = $duty->toArray();
        $this->assign('duty', $duty);
        $this->assign('project_id', $project_id);
        $this->assign('arr', $arr);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="添加")
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
            try {
                $save = $this->model->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败:' . $e->getMessage());
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit($id)
    {
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
            try {
                $save = $row->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $this->assign('row', $row);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="删除")
     */
    public function delete($id)
    {
        $this->checkPostRequest();
        $row = $this->model->whereIn('id', $id)->select();
        $row->isEmpty() && $this->error('数据不存在');
        try {
            $save = $row->delete();
        } catch (\Exception $e) {
            $this->error('删除失败');
        }
        $save ? $this->success('删除成功') : $this->error('删除失败');
    }

    /**
     * @NodeAnotation(title="导出")
     */
    public function export()
    {
        list($page, $limit, $where) = $this->buildTableParames();
        $tableName = $this->model->getName();
        $tableName = CommonTool::humpToLine(lcfirst($tableName));
        $prefix    = config('database.connections.mysql.prefix');
        $dbList    = Db::query("show full columns from {$prefix}{$tableName}");
        $header    = [];
        foreach ($dbList as $vo) {
            $comment = !empty($vo['Comment']) ? $vo['Comment'] : $vo['Field'];
            if (!in_array($vo['Field'], $this->noExportFields)) {
                $header[] = [$comment, $vo['Field']];
            }
        }
        $list     = $this->model
            ->where($where)
            ->limit(100000)
            ->order('id', 'desc')
            ->select()
            ->toArray();
        $fileName = time();
        return Excel::exportData($list, $header, $fileName, 'xlsx');
    }

    /**
     * @NodeAnotation(title="属性修改")
     */
    public function modify()
    {
        $this->checkPostRequest();
        $post = $this->request->post();
        $rule = [
            'id|ID'    => 'require',
            'field|字段' => 'require',
            'value|值'  => 'require',
        ];
        $this->validate($post, $rule);
        $row = $this->model->find($post['id']);
        if (!$row) {
            $this->error('数据不存在');
        }
        if (!in_array($post['field'], $this->allowModifyFields)) {
            $this->error('该字段不允许修改：' . $post['field']);
        }
        try {
            $row->save([
                $post['field'] => $post['value'],
            ]);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('保存成功');
    }

    /**
     * @NodeAnotation(title="结构树")
     */
    public function tree()
    {
        $param      = $this->request->get();
        $project_id = isset($param['project_id']) ? $param['project_id'] : 1;
        $list       = getProjectTreeData($project_id);
        return $list;
    }

    public function archivesFile()
    {
        $param       = $this->request->get();
        $archives_id = $param['id'];

        if ($this->request->isAjax()) {
            $page  = $param['page'] ?? 1;
            $limit = $param['limit'] ?? 15;
            $where = [];
            if (isset($param['keyword']) && !empty($param['keyword'])) {

                $where[] = ['name', 'like', '%' . $param['keyword'] . '%'];
            }
            $archivesFile = Db::name("archives_file")->where('archives_id', $archives_id)->where($where)->order('start_page_number asc')->page($page, $limit)->select();
            $archivesFile = $archivesFile->all();
            $total        = Db::name("archives_file")->where('archives_id', $archives_id)->count();
            foreach ($archivesFile as $k => $v) {
                $archivesFile[$k]['keys'] = $limit * ($page - 1) + $k + 1;
                if ($v['time']) {
                    $archivesFile[$k]['time'] = date('Ymd', $v['time']);
                }

            }


            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $total,
                'data'  => $archivesFile,
            ];
            return json($data);
        }
        $archivesAdmin = Db::name('archives_admin')->where('id', $archives_id)->find();
        $page_number   = Db::name("archives_file")->where('archives_id', $archives_id)->order('start_page_number desc')->field('id,end_page_number')->find();

        $file['page_number']          = empty($page_number) ? 0 : $page_number['end_page_number'];
        $total                        = Db::name("archives_file")->where('archives_id', $archives_id)->count();
        $archivesAdmin['page_number'] = empty($page_number) ? 0 : $page_number['end_page_number'];
        $archivesAdmin['explain']     = "共" . $total . "件，共" . $file['page_number'] . "页";
        $archivesAdmin['start_time']  = date('Ymd', $archivesAdmin['start_time']);
        $archivesAdmin['end_time']    = date('Ymd', $archivesAdmin['end_time']);
        $this->assign('archivesAdmin', $archivesAdmin);
        return $this->fetch();
    }

    public function archivesBorrow()
    {
        $get = $this->request->get();
        if ($this->request->isPost()) {
            $param = $this->request->post();
            if (empty($param['filename'])) {
                if ($param['type'] == 1) {
                    $this->error('案卷名称不能为空');
                } else if ($param['type'] == 2) {
                    $this->error('文件名称不能为空');
                }

            }
            if (empty($param['reference'])) {
                $this->error('档案号不能为空');
            }
            if (empty($param['borrowers'])) {
                $this->error('借阅人不能为空');
            }
            if (empty($param['handled'])) {
                $this->error('经办人不能为空');
            }
            if (empty($param['times'])) {
                $this->error('借出时间不能为空');
            }
            $insert = [
                'type'        => $param['type'],
                'status'      => $param['status'],
                'filename'    => $param['filename'],
                'reference'   => $param['reference'],
                'borrowers'   => $param['borrowers'],
                'handled'     => $param['handled'],
                'times'       => $param['times'],
                'remark'      => $param['remark'],
                'create_time' => time()
            ];


            $res = Db::name('mall_borrow')->insert($insert);
            if ($res) {
                $this->success('操作成功！');
            } else {
                $this->error('借阅失败！');
            }
        }
        $data              = Db::name('archives_file')->where('id', $get['id'])->find();
        $data['types']     = $get['type'];
        $data['reference'] = $get['reference'];
        $this->assign('data', $data);
        return $this->fetch();
    }

    public function archivesShow()
    {
        $get  = $this->request->get();
        $data = Db::name('archives_file')->where('id', $get['id'])->find();
        if($data['plat']==2){
            $url  = 'https://qcs.qichenglantai.com/' . $data['url'];
        }else{
            $url  = 'https://qc.qichenglantai.com/' . $data['url'];
        }

        echo "<script>window.location.href=" . $url . "</script>";
        exit();
    }

    public function archivesXml()
    {
        return $this->fetch();
    }
}